<template>
  <div class="track_the_playback">
    <!-- 地图 -->
    <div class="container" style="padding: 0px">
      <div id="map"></div>
      <div class="map-operation">
        <ul>
          <li
            v-for="(item, index) in mapOperationsList"
            :class="{ active: item.active }"
            :key="index"
            @click="changeOperationValue(item, index)"
          >
            <!-- <i :class="item.icon"></i> -->
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div>
    <!-- 右键列表菜单 -->
    <div
      class="row_box"
      v-if="MouseEvent.isShow"
      :style="`left: ${MouseEvent.left}px; top: ${MouseEvent.top}px;`"
    >
      <span @click="editOverlay">编辑</span>
      <!-- <span @click="goPhoto">图片</span> -->
    </div>
    <!-- 弹出框 地图点位信息框 -->
    <el-dialog title="点位信息" :visible.sync="formPointOnMap.show" width="50%">
      <el-form
        ref="formPointOnMap"
        :model="formPointOnMap"
        label-width="140px"
        class="flex"
      >
        <el-form-item label="点位名称：" style="width: 40%">
          <el-input v-model="formPointOnMap.data.PointName" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="所属车辆：" style="width: 40%">
          <el-input
            v-model="formPointOnMap.data.LICENSE_PLATE"
            :disabled="true"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="formPointOnMap.way">
            <el-radio-button label="重新分配"></el-radio-button>
            <el-radio-button label="临时调度"></el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form
        v-if="formPointOnMap.way === '重新分配'"
        ref="formPointOnMap"
        :model="formPointOnMap"
        label-width="140px"
        class="flex"
      >
        <el-form-item label="车辆：">
          <el-select
            style="width: 177px"
            v-model="formPointOnMap.newPlanID"
            :options="optionsCarPlaned"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in optionsCarPlaned"
              :key="item.ID"
              :label="item.LICENSE_PLATE"
              :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        v-if="formPointOnMap.way === '临时调度'"
        ref="formPointOnMap"
        :model="formPointOnMap"
        label-width="140px"
        class="flex"
      >
        <el-form-item label="车辆：">
          <el-select
            style="width: 177px"
            v-model="formPointOnMap.newPlanID"
            :options="optionsCarPlaned"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in optionsCarPlaned"
              :key="item.ID"
              :label="item.LICENSE_PLATE"
              :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调度时间：">
          <el-date-picker
            v-model="formPointOnMap.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formPointOnMap.show = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitPointToNewPlan()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MapStr from '@/main.js'
import eventBus from '@/eventBus.js'
import { newMap } from '@/common/js/map.js'
import { formatDate } from '@/common/js/date.js'
import closeBtnImg from '@/assets/img/define.png'
// import imgMarkerRubbishPoint from '@/assets/img/marker/rubbishMarker1.png'
export default {
  data () {
    return {
      arrPointIn: [],
      map: null,
      mapCursor: null,
      mapZoom: 10,
      VID: '',
      dataPlannedRoute: [],
      polygonPlannedRoute: [],
      dataRubbishPoints: [],
      optionsCarPlaned: [],
      pointArrRubbishPoints: [],
      arrPointIn: [],
      planID: '',
      MouseEvent: {
        top: 0,
        left: 0,
        isShow: false
      },
      MapV: {
        iconLayerDic: {},
        textLayerDic: {},
        dataSetDic: {}
      },
      mapDrawingManager: null,
      mapOperationsList: [{
        name: '显示已规划分区',
        icon: 'el-icon-truck',
        active: false
      }, {
        name: '新建分区',
        icon: 'el-icon-truck',
        active: false
      }, {
        name: '测距',
        icon: 'el-icon-knife-fork',
        active: false
      }],
      formPointOnMap: {
        way: '',
        time: [],
        newPlanID: '',
        data: {},
        show: false
      },
      isZoomChange: 'S'
    }
  },
  created () {
    // 自动刷新 + 显示计划路线多边形
    eventBus.$on('getPlanDrawPolygon', val => {
      this.dataPlannedRoute = val
    })
    eventBus.$on('getCarPlaned', val => {
      this.optionsCarPlaned = val

      // this.drawPlanPolygon();
    })
    // 双击人员列表某一行，显示标记点，信息窗体
    eventBus.$on('mapLocaltionPlan', val => {
      var arrayPoint = []
      val.forEach(element => {
        arrayPoint.push(new BMap.Point(element.LONGITUDE, element.LATITUDE))
      })
      this.map.setViewport(arrayPoint)
      // this.map.centerAndZoom(new BMap.Point(val.LONGITUDE, val.LATITUDE), 14)// 初始化地图,设置中心点坐标和地图级别
    })
  },
  mounted () {
    // 显示地图
    this.mapShow()
    this.getPlacePointApi()
    // window.theCarBePlaned = this.theCarBePlaned;
  },
  methods: {
    async handleSubmitPointToNewPlan () {
      console.log(this.formPointOnMap)
      var url = 'DataListCompany/ChangePointToNewPlan?FROMID=' + this.formPointOnMap.data.PLAN_ID + '&TOID=' + this.formPointOnMap.newPlanID + '&POINTID=' + this.formPointOnMap.data.ID
      if (this.formPointOnMap.way === '临时调度') {
        url = 'DataListCompany/ChangePointToNewPlanTemporary?FROMID=' + this.formPointOnMap.data.PLAN_ID + '&TOID=' + this.formPointOnMap.newPlanID + '&POINTID=' + this.formPointOnMap.data.ID +
          '&STARTTIME=' + formatDate(this.formPointOnMap.time[0], 'yyyy-MM-dd hh:mm:ss') + '&ENDTIME=' + formatDate(this.formPointOnMap.time[1], 'yyyy-MM-dd hh:mm:ss')
      }
      console.log(url)
      const { data } = await this.$Http.get(url)
      console.log(data)
      if (data.IsSucess) {
        this.$message.success('操作成功')
        this.formPointOnMap.show = false
        this.getPlacePointApi()
      } else {
        this.$message.error(data.Message)
      }
    },
    // 计算点位与多边形重合范围
    isPointInPolygon (overlay) {
      this.arrPointIn = []

      this.dataRubbishPoints[0].forEach(element => {
        var result = BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(element.LONGITUDE, element.LATITUDE), overlay)
        if (result) {
          element.PointID = element.ID
          element.PointName = element.NAME
          element.Stime = '05:00'
          element.Etime = '23:00'
          element.Wtime = '100'
          element.LONGITUDE = element.LONGITUDE_GPS
          element.LATITUDE = element.LATITUDE_GPS
          this.arrPointIn.push(element)
        }
      })
      if (overlay.ID) {
        var itemPlan = this.dataPlannedRoute.filter(item => item.ID === overlay.ID)[0]
        this.dataRubbishPoints[1].forEach(element => {
          var result = BMapLib.GeoUtils.isPointInPolygon(new BMap.Point(element.LONGITUDE, element.LATITUDE), overlay)
          if (result) {
            var arrayPoint = itemPlan.PlanLinePoints.filter(itemPoint => itemPoint.PointID === element.ID.toString())

            if (arrayPoint.length > 0) {
              arrayPoint[0].LONGITUDE = element.LONGITUDE_GPS
              arrayPoint[0].LATITUDE = element.LATITUDE_GPS
              this.arrPointIn.push(arrayPoint[0])
            }
          }
        })
        eventBus.$emit('getPointsFromMap', { plan: itemPlan, arrayPointIn: this.arrPointIn })
      } else {
        eventBus.$emit('getPointsFromMap', { plan: {}, arrayPointIn: this.arrPointIn })
      }
    },
    // 显示地图
    mapShow () {
      // 百度地图API功能
      this.map = newMap()
      this.map.centerAndZoom(new BMap.Point(localStorage.getItem('LNG'), localStorage.getItem('LAT')), this.mapZoom)// 初始化地图,设置中心点坐标和地图级别
      // this.map.disableDoubleClickZoom();

      // 缩放屏幕
      const _this = this
      this.map.addEventListener('zoomend', function (e) {
        // console.log("地图缩放至：" + this.getZoom() + "级");
        // var aa = e.target.getZoom();
        if (e.target.getZoom() > 13 && _this.isZoomChange === 'S') {
          _this.isZoomChange = 'B'
          for (var key in _this.MapV.textLayerDic) {
            _this.MapV.textLayerDic[key].show()
          }
          _this.drawRubbishPoints()
        }
        if (e.target.getZoom() < 14 && _this.isZoomChange === 'B') {
          _this.isZoomChange = 'S'
          for (var key1 in _this.MapV.textLayerDic) {
            _this.MapV.textLayerDic[key1].hide()
          }
          _this.drawRubbishPoints()
        }
      })
    },
    // 改变右上方显示隐藏图标
    changeOperationValue (item, index) {
      switch (index) {
        case 0:
          this.drawPlanPolygon()
          break
        case 1:
          this.setDrawingManager()
          break
        case 2:
          this.setDistance()
          break
      }
    },
    // 测距
    setDistance () {
      if (!this.mapCursor) {
        this.mapCursor = new BMapLib.DistanceTool(this.map)
      }
      if (this.mapCursor.isOpen) {
        // 结束测量
        this.mapCursor.close()
      } else {
        // 开始测量
        this.mapCursor.open()
      }
    },
    // 划分片区
    setDrawingManager () {
      this.planID = 0
      // 电子围栏 初始化
      if (!this.mapDrawingManager) {
        // 实例化绘图工具
        this.mapDrawingManager = new BMapLib.DrawingManager(this.map, {
          // enableDrawingTool: true,//工具栏
          drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            offset: new BMap.Size(5, 5)
          }
        })
        const _this = this
        // 监听绘制结果
        this.mapDrawingManager.addEventListener('polygoncomplete', function (e, overlay) {
          // this.mapDrawingManager.addEventListener('overlaycomplete', res => {

          overlay.addEventListener('click', function (type, target, point, pixel) {
            this.ID = null
            _this.editOverlay(this)
          })
          overlay.ID = null
          _this.editOverlay(overlay)
        })
        this.mapDrawingManager.setDrawingMode('polygon')
      }
      if (this.mapDrawingManager.isOpen) {
        // 结束画图
        this.mapDrawingManager.close()
      } else {
        // 开始画图
        this.mapDrawingManager.open()
      }
      // 开始画图
      // this.mapDrawingManager.open()
    },
    // 编辑多边形
    editOverlay (overlay) {
      overlay.type = 'draw'
      overlay.enableEditing() // 设置电子围栏可编辑
      var m = new BMap.Icon(closeBtnImg, new BMap.Size(40, 40))
      var closeBtn = new BMap.Marker(overlay.getBounds().getNorthEast(), { icon: m, offset: new BMap.Size(0, -15) })
      this.map.addOverlay(closeBtn)
      // closeBtn.setTitle("\u6e05\u9664\u672c\u6b21\u6d4b\u8ddd");
      const _this = this
      closeBtn.addEventListener('click', function (r) {
        overlay.disableEditing()
        _this.isPointInPolygon(overlay)
        _this.map.removeOverlay(this)
      })
    },
    // 获取垃圾点
    async getPlacePointApi () {
      var url = 'DataListCompany/GetPlacePointApi'
      const { data } = await this.$Http.get(url)
      var arrayPlaned = []; var arrayPlanNo = []
      data.forEach(element => {
        if (element.LICENSE_PLATE) {
          element.image = '1'
          arrayPlaned.push(element)
        } else {
          element.image = '0'
          arrayPlanNo.push(element)
        }
      })
      this.dataRubbishPoints = [arrayPlanNo, arrayPlaned]
      eventBus.$emit('dataRubbishPoints', this.dataRubbishPoints)
      this.drawRubbishPoints()
    },
    // 画途经垃圾点位
    drawRubbishPoints () {
      // var mapv = require('mapv')
      for (var key in this.MapV.dataSetDic) {
        this.MapV.dataSetDic[key].set([])
      }
      const _self = this
      var pointArrRubbishPoints = []
      this.dataRubbishPoints.forEach(element => {
        const img = new Image()
        // img.src = imgMarkerRubbishPoint
        img.src = require('@/assets/img/marker/PlanPoint' + element[0].image + this.isZoomChange + '.png')
        img.onload = function () {
          const key = element[0].image
          // 循环加载同一张图片的车辆数据
          const arrayImage = element.map(v => {
            v.geometry = {
              type: 'Point',
              coordinates: [v.LONGITUDE, v.LATITUDE]
            }
            v.icon = img
            v.text = v.NAME
            pointArrRubbishPoints.push(new BMap.Point(v.LONGITUDE, v.LATITUDE))
            return v
          })

          if (_self.MapV.dataSetDic.hasOwnProperty(key)) {
            _self.MapV.dataSetDic[key].set(arrayImage)
          } else {
            _self.map.setViewport(pointArrRubbishPoints)
            const optionsICON = {
              zIndex: -1,
              draw: 'icon',
              size: 30,
              width: 30, // 规定图像的宽度
              height: 30, // 规定图像的高度
              methods: { // 一些事件回调函数
                click: function (item, event) { // 点击事件，返回对应点击元素的对象值.
                  if (item) {
                    // _self.formPoint.title = item.ID + '-' + item.NAME
                    item.PointName = item.NAME
                    item.PointID = item.ID
                    // _self.formPoint.data.LATITUDE = item.LATITUDE
                    // _self.formPoint.data.LONGITUDE = item.LONGITUDE
                    // 信息窗体
                    // const opts = {
                    //   width: 200,     // 信息窗口宽度
                    //   height: 120,     // 信息窗口高度
                    //   title: '点位信息', // 信息窗口标题
                    // }
                    // var str = '<p style="margin-top: 5px;margin-bottom: 5px;">点位名称：'+item.NAME+'</p>'
                    // if (item.LICENSE_PLATE) {
                    //   str += '<p style="margin-bottom: 5px;">所属车辆：'+item.LICENSE_PLATE+'</p>'
                    //   // str += '<INPUT style="margin-bottom: 5px;" onclick=theCarBePlaned(' + item + ') type=button value=重新分配>'
                    // } else {
                    //   str += '未分配所属车辆'
                    //   // str += '<INPUT style="margin-bottom: 5px;" onclick=theCarBePlaned(' + item + ') type=button value=分配车辆>'
                    //   str += '<button @click="theCarBePlaned">Delete</button>'
                    //   // str += '<div onClick="theCarBePlaned">Delete</div>'
                    // }
                    // _self.map.openInfoWindow(new BMap.InfoWindow(str, opts), new BMap.Point(item.LONGITUDE, item.LATITUDE));
                    // 转移事件
                    // eventBus.$emit('clickPointOnMap', item)
                    _self.formPointOnMap.show = true
                    _self.formPointOnMap.data = item
                  }
                }
              }
              // offset: { // 偏移值
              //   x: 0,
              //   y: 25
              // }
            }
            const optionsTEXT = {
              zIndex: -1,
              draw: 'text',
              avoid: true, // 开启文本标注避让
              textBaseline: 'middle',
              offset: { // 文本便宜值
                x: 0,
                y: 20
              }
            }
            var dataSet = new mapv.DataSet(arrayImage)
            _self.MapV.dataSetDic[key] = dataSet
            _self.MapV.iconLayerDic[key] = new mapv.baiduMapLayer(_self.map, dataSet, optionsICON)
            _self.MapV.textLayerDic[key] = new mapv.baiduMapLayer(_self.map, dataSet, optionsTEXT)
            for (var key1 in _self.MapV.textLayerDic) {
              _self.MapV.textLayerDic[key1].hide()
            }
          }
        }
      })
    },
    // theCarBePlaned () {
    //   // 删一个数组元素
    //   // this.people.splice(index,1);
    //   console.log('theCarBePlaned')
    // },
    // 画出各个计划路线边框多边形
    drawPlanPolygon () {
      if (this.polygonPlannedRoute.length) {
        if (this.mapOperationsList[0].active) {
          this.polygonPlannedRoute.forEach(element => {
            this.mapOperationsList[0].active = false
            this.mapOperationsList[0].name = '显示已规划分区'
            element.hide()
          })
        } else {
          this.polygonPlannedRoute.forEach(element => {
            this.mapOperationsList[0].active = true
            this.mapOperationsList[0].name = '隐藏已规划分区'
            element.show()
          })
        }
      } else {
        this.mapOperationsList[0].active = true
        this.mapOperationsList[0].name = '隐藏已规划分区'
        var dataAllPolygon = []
        this.dataPlannedRoute.forEach(plan => {
          var pointsTurf = []
          var points = []
          if (plan.PlanLinePoints.length > 3) {
            plan.PlanLinePoints.forEach(point => {
              pointsTurf.push(turf.point([point.LONGITUDE, point.LATITUDE]))
            })
            // 凸包点位数据，生成多边形顶点，矫正顶点顺序
            var hull = turf.convex(turf.featureCollection(pointsTurf))
            // console.log(hull);

            hull.geometry.coordinates[0].forEach(element => {
              points.push(new BMap.Point(element[0], element[1]))
              // points.push([element[0], element[1]])
            })
          } else {
            plan.PlanLinePoints.forEach(point => {
              points.push(new BMap.Point(point.LONGITUDE, point.LATITUDE))
              // points.push([point.LONGITUDE, point.LATITUDE])
            })
          }
          var polygon = new BMap.Polygon(points, {
            strokeColor: 'rgba(58, 107, 219, 1)',
            strokeWeight: 3,
            strokeStyle: 'dashed',
            fillColor: 'rgba(255, 255, 255, 0.65)'
          })
          polygon.ID = plan.ID
          const _this = this
          polygon.addEventListener('dblclick', function (oEvent) {
            _this.planID = this.ID
            // _this.MouseEvent.left = oEvent.clientX
            // _this.MouseEvent.top = oEvent.clientY
            // _this.MouseEvent.isShow = true

            // console.log(this.ID)
            _this.editOverlay(this)
          })
          // polygon.addEventListener("mouseout", function (oEvent) {
          //   _this.MouseEvent.isShow = false;
          // });
          this.map.addOverlay(polygon)
          this.polygonPlannedRoute.push(polygon)
        })
        // var dataSet = new mapv.DataSet(dataAllPolygon);
        // var options = {
        //   zIndex: 10,
        //   fillStyle: 'rgba(255, 255, 255, 0.65)', // 填充颜色
        //   strokeStyle: 'rgba(58, 107, 219, 0.65)', // 描边颜色
        //   lineWidth: 5,
        //   lineJoin: 'round',
        //   methods: { // 一些事件回调函数
        //     click: function (item, event) { // 点击事件，返回对应点击元素的对象值.
        //       if (item) {
        //         console.log(item);
        //       }
        //     }
        //   }
        // }
        // new mapv.baiduMapLayer(this.map, dataSet, options)
      }
    }
  }
}
</script>

<style scoped lang="less">
.track_the_playback {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .container {
    flex: 1;
    #map {
      height: 100% !important;
      // height: 800px;
      width: 100%;
    }
  }
}
.row_box {
  width: 120px;
  color: #666;
  background-color: #f3f3f3;
  border: 1px solid #ccc;
  position: fixed;
}
.row_box span {
  display: block;
  text-align: center;
  line-height: 26px;
  cursor: default;
}
.row_box span:hover {
  color: #fff;
  background-color: #409eff;
}
.map-operation {
  position: absolute;
  right: 20px;
  top: 60px;
  background: rgba(255, 255, 255, 0.9);
  // border: 1px solid #dcdfe6;
  box-shadow: 1px 1px 5px #666;
  border-radius: 3px;
  ul {
    li {
      list-style: none;
      float: left;
      color: #666;
      font-size: 15px;
      padding: 5px 12px;
      position: relative;
      cursor: pointer;
      i {
        margin-right: 3px;
        // font-size: 14px;
        // &:before {
        //   font-size: inherit;
        //   color: inherit;
        // }
      }
      &::before {
        display: block;
        content: '';
        width: 1px;
        height: 13px;
        background: #dcdfe6;
        position: absolute;
        right: 0;
        top: 8px;
      }
      // &:last-child {
      //   &::before {
      //     display: none;
      //   }
      // }
      // &.active {
      //   color: #007acc;
      // }
    }
  }
}
</style>
